<template>
  <div class="login_container">
    <!--
            一行有24格，
            :xs表示如果屏幕宽度小于768px，那么左半边就不显示，全都显示右半边的内容
        -->
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
          <h1>Hello</h1>
          <h2>欢迎来到徐鹏的项目</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" v-model="loginForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="login">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'

// 引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
//引入获取当前时间的函数
import { getTime } from "@/utils/time";

let useUser = useUserStore()

// 获取路由器
let $router = useRouter()

// 定义变量控制按钮加载效果
let loading = ref(false)

// 收集账号和密码的数据
let loginForm = reactive({ username: 'admin', password: '111111' })

// 获取el-form组件
let loginForms = ref()

// 登录按钮回调
const login = async () => {
  // 保证全部表单项校验通过再发请求
  await loginForms.value.validate()

  // 按钮加载效果
  loading.value = true

  try {
    // 保证登录成功
    await useUser.userLogin(loginForm)

    // 跳转
    $router.push('/')

    // 提示
    ElNotification({
      type: 'success',
      message: '登录成功',
      title: `HI,${getTime()}好`,
    })

    loading.value = false
  } catch (error) {
    loading.value = false

    // 提示
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

// 定义表单校验需要配置对象
const rules = {
  username: [
    // trigger:blur-失去焦点的时候触发校验。change-发生变化的时候触发校验
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, max: 10, message: '账号长度至少4位最大10位', trigger: 'change' }
  ],
  password: [
    { required: true, min: 6, max: 15, message: '密码最少6位最大15位', trigger: 'change' }
  ]
}


</script>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh; //视图区域撑满
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover; //把div全都覆盖

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0px; //上下间隔20px，左右间隔0px
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>